import {connect} from "react-redux";
import React, {useEffect, useState} from "react";
import '../../../assets/scss/pages/tasks.scss'
import {Check, Info, PlusCircle, Star, Tag} from "react-feather";
import Checkbox from "../../../components/@vuexy/checkbox/CheckboxesVuexy";
import {FileUpload} from "../../../components/general/FileUpload";
import DataAndTime from "./DataAndTime";
import {Button, Fade, Modal} from "reactstrap";
import {setFieldData, setFieldIdData} from "../../../redux/actions/helper";
import {SET_TASK_FIELD, SET_TASK_FILE, SET_TASKS_FIELD} from "../../../redux/constants/tasks";
import {getTask, storeTask, updateTask} from "../../../redux/actions/tasks";
import {CloseIcon} from "../events/eventDetail/icons";
import SelectTags from "../../../components/general/SelectTags";
import TagModal from "./tag-modal";

const AddTaskForm = props => {
  const {minHeight, params, task, reqParams, tags} = props
  const {setFieldData, setFieldIdData, getTask, updateTask, storeTask} = props
  const [nameValid, setNameValid] = useState(false)

  const fileUploaded = file => {
    setFieldData(SET_TASK_FILE, 'file', file)
  }

  const setDate = date => {
    setFieldData(SET_TASK_FIELD, 'task', {...task, ending_at: date})
  }

  const handleClickOutside = event => {
    let AddTaskForm = document.getElementById('AddTaskForm')
    let AddTaskFormContent = document.getElementById('AddTaskForm-content')
    if (AddTaskForm && AddTaskForm.contains(event.target)) {
      if (AddTaskFormContent && AddTaskFormContent.contains(event.target)){
        console.log('noclose')
      }else{
        close()
      }

    }
  };

  const close = ()=>{
    setFieldIdData(SET_TASK_FIELD, 'params', {
      ...params,
      task_id: null,
      isOpenModal: false
    })
    setFieldIdData(SET_TASK_FIELD, 'task', {tags: [],files: {}})
  }

  const changeTags = (tags) => {
    setFieldData(SET_TASK_FIELD, 'task', {...task, tags: tags})
  }

  const Save = () => {
    if (task.name){
      if (params.task_id !== null)
        updateTask(params.task_id, task, reqParams)
      else
        storeTask(task,reqParams)
    }else{
      setNameValid(true)
    }
  }

  useEffect(() => {
    if (params.task_id)
      getTask(params.task_id, reqParams)
    else
      setFieldData(SET_TASK_FIELD, 'task', {
        completed: 0,
        description: "",
        ending_at: Math.round((new Date()).getTime() / 1000),
        important: 0,
        name: "",
        starred: 0,
        tags: [],
        files: {},
      })
  }, [])

  useEffect(() => {
    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    }
  }, [])

  return (
    <div id="AddTaskForm" className="AddTaskForm d-flex py-lg-2 py-0">
      <div className="AddTaskForm-body w-100 h-100 flex-grow-1 d-flex justify-content-end">
        <div id="AddTaskForm-content" className="AddTaskForm-content position-relative">
          <h5 className="p-1 mr-3">Добавить/Редактировать задачу</h5>
          <div onClick={close} className="position-absolute m-1 position-right-0 position-top-0 cursor-pointer">
            <CloseIcon size={20}/>
          </div>

          <div className="p-1 d-flex justify-content-between">
            <Checkbox
              className="mr-1"
              color="primary"
              icon={<Check className="vx-icon" size={16}/>}
              checked={task.completed}
              label="Открыта"
              value={task.id}
              onChange={e => setFieldData(SET_TASK_FIELD, 'task', {...task, completed: e.target.checked})}
            />
            <div className="actions d-flex align-items-center">
              <Star size={20}
                    onClick={() => setFieldData(SET_TASK_FIELD, 'task', {...task, starred: !task.starred})}
                    className={`mr-1 star-btn ${task.starred ? 'active' : ''}`}/>
              <Info size={20}
                    onClick={() => setFieldData(SET_TASK_FIELD, 'task', {...task, important: !task.important})}
                    className={`mr-1 info-btn ${task.important ? 'active' : ''}`}/>
              <Tag size={20}
                   onClick={() => setFieldData(SET_TASK_FIELD, 'params', {...params, isTagsOpen: !params.isTagsOpen})}
                   className={`mr-1 tag-btn`}/>
            </div>
          </div>

          <Fade in={params.isTagsOpen} unmountOnExit>
            <TagModal/>
            <div className="SelectTags position-relative d-flex justify-content-between p-1">
              <SelectTags length={3} className="flex-grow-1 mr-1" changeTags={changeTags} selected={task.tags}
                          tags={tags}
                          type={'Task'}/>
              <div className="task__add-tag d-flex align-items-center cursor-pointer"
                   onClick={() => {
                     setFieldData(SET_TASK_FIELD, 'params', {...params, isTagsModal: true})
                   }}>
                <PlusCircle size={18}/>
              </div>
            </div>
          </Fade>


          <div className="p-1 mt-2">
            <input placeholder={'Введите название'}
                   id="name"
                   value={task.name || ''}
                   onChange={e => {
                     setNameValid(e.target.value.length === 0)
                     setFieldData(SET_TASK_FIELD, 'task', {...task, name: e.target.value})
                   }}
                   className={`form-control input ${nameValid ? 'custom-input-invalid' : ''}`}/>

            <textarea
              placeholder={'Описание задачи с ограничением по кол-ву символов в 1000 '}
              value={task.description || ''}
              onChange={e => setFieldData(SET_TASK_FIELD, 'task', {...task, description: e.target.value})}
              rows={4}
              className={`form-control textarea my-3`}
            />

            <FileUpload type={'Task'} file={task.files} fileUploaded={fileUploaded}/>

            <DataAndTime
              date={task.ending_at}
              setDate={setDate}
            />

            <div className="d-flex task-tags mt-2 w-100">
              {
                task.tags.map(value => {
                  return <div className="d-flex task-tag align-items-center mr-1">
                    <p className="m-0">{value.name}</p>
                    <div className="tag-badge ml-1" style={{backgroundColor: value.color}}/>
                  </div>
                })
              }
            </div>

            <hr className="my-3"/>

            <div className="d-flex justify-content-end flex-wrap">
              <div className="mr-1 mb-1">
                <Button.Ripple
                  onClick={close}
                  outline
                  color="danger" className="btn-uppercase">
                  Отмена
                </Button.Ripple>
              </div>
              <div className="mr-1 mb-1">
                <Button.Ripple onClick={Save} outline color="primary" className="btn-uppercase">
                  Сохранить
                </Button.Ripple>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}

const mapStateToProps = state => ({
  params: state.tasks.params,
  task: state.tasks.task,
  reqParams: state.tasks.reqParams,
  tags: state.tags.tags,
});
export default connect(mapStateToProps, {setFieldData, setFieldIdData, getTask, updateTask, storeTask})(AddTaskForm)
